<template>
    <el-dialog v-model="visible" @close="closePage" title="模型设计" fullscreen>
        <iframe v-loading="loading" src="https://goldsubmarine.github.io/workflow-bpmn-modeler/cdn/0.2.8/" id="myFrame"
            frameborder="0" width="100%" height="800px">
        </iframe>
    </el-dialog>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { queryBpmnXmlReq, designReq } from '@/api/workflow/model/index.js'
import { success, failed, info } from '@/utils/messageUtils.js';

const props = defineProps({
    bpmnUsers: Array,
    bpmnRoles: Array,
    bpmnCategories: Array,
    querySelective: Function
})

const visible = ref(false)
const loading = ref(false)

const open = (row) => {
    visible.value = true;
    loading.value = true;
    nextTick(() => {
        const myFrame = document.getElementById("myFrame");
        // 重置 iframe 内容以确保可以重新发送消息
        myFrame.src = myFrame.src;
        // 注册监听 message 事件,保存bpmn
        window.addEventListener("message", (event) => {
            console.log(event.data); // { xml: 'xxx', svg: 'xxx', process: {id:'',name:'',category:''} }
            const designParam = {
                modelId: row.id,
                xml: event.data.xml
            }
            designReq(designParam).then(res => {
                if (res.code == 200) {
                    success("保存模型设计成功！");
                }
            })
        });
        myFrame.onload = () => sendBpmnDataToIframe(myFrame, row.id);
    });
}

const sendBpmnDataToIframe = (myFrame, rowId) => {
    queryBpmnXmlReq(rowId).then((bpmnXmlRes) => {
        let postMsg = {
            xml: bpmnXmlRes.data, // 后端查询到的 xml，新建则为空串
            users: JSON.parse(JSON.stringify(props.bpmnUsers)),
            groups: JSON.parse(JSON.stringify(props.bpmnRoles)),
            categorys: JSON.parse(JSON.stringify(props.bpmnCategories)),
            isView: false
        };
        myFrame.contentWindow.postMessage(postMsg, "*");
        loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
}

defineExpose({
    open,
})

// 关闭dialog
const closePage = () => {
    props.querySelective();
    visible.value = false;
}
</script>